const Focus = require('../modules/recommend/focusDetail')
const Detail = require('../modules/base/cosmeticsDetail')
const Like = require('../modules/recommend/likeClassify')
const Map = require('../modules/map/classifyFieldMap')

const Op = require('sequelize').Op

class Analysis {
  /**
   * 获取用户关注集合
   */
  static async focusAnalysis(ctx) {
    const focusList = await Focus.getFocus({}, 'detailId')
    console.log(focusList)
    let current
    let count = 1
    let hotFocus = []
    focusList.forEach(item => {
      if (item.detailId === current) {
        count = count + 1
      } else {
        current && (hotFocus.push({
          detailId: current,
          count,
          detail: null
        }))
        current = item.detailId
        count = 1
      }
    })
    hotFocus = hotFocus.sort((a, b) => {
      return b.count - a.count
    }).slice(0, 20)
    // let select = hotFocus.map(item => { return {classify: {[Op.like]: `%${item.detailId}%`}} })
    for(var i = 0; i < hotFocus.length; i++) {
      let detail
      await (function(){
        return new Promise(function(res, rej){
          (async () => {
            detail = await Detail.getCosmeticsDetailItem({
              detail_id: hotFocus[i].detailId
            })
            // console.log(detail)
            res()
          })()
        })
      }())
      hotFocus[i].detail = detail
    }
    ctx.body = {
      code: 200,
      data: {
        list: hotFocus,
        total: hotFocus.length
      }
    }
  }

  /**
   * 偏好数据
   */
  static async likeAnalysis(ctx) {
    const likes = await Like.getAllLikeClassify({})
    let classify = []

    likes.forEach(item => {
      classify = classify.concat(JSON.parse(item.classifyKey))
    })
    classify = classify.sort()

    const map = await Map.getMap({})
    
    let hotClassify = []
    let current
    let count = 1
    classify.forEach(item => {
      if(item === current) {
        count = count + 1
      } else {
        current && (hotClassify.push({
          key: current,
          count,
          label: null
        }))
        current = item,
        count = 1
      }
    })
    hotClassify = hotClassify.sort((a, b) => {
      return b.count - a.count
    }).slice(0, 20)

    for(var i = 0; i < hotClassify.length; i++) {
      await (function(){
        return new Promise(function(res, rej){
          (async () => {
            let item = (await Map.getMap({
              key: hotClassify[i].key
            }))[0]
            hotClassify[i].label = `${item.content}-${item.value}`
            res()
          })()
        })
      }())
    }

    ctx.body = {
      code: 200,
      data: {
        list: hotClassify,
        total: hotClassify.length
      }
    }
  }
}

module.exports = Analysis
